package com.demo2do.boyle.client.service.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Service;

import com.demo2do.boyle.client.cpc.util.AdvancedUtil;
import com.demo2do.boyle.client.cpc.util.CookieUtil;
import com.demo2do.boyle.client.cpc.util.WeixinOauth2Token;
import com.demo2do.boyle.client.service.CpcService;
import com.demo2do.boyle.common.entity.cpc.Cpc;
import com.demo2do.core.persistence.GenericJdbcSupport;
import com.demo2do.core.service.impl.GenericServiceImpl;

/**
 * 
 * @author Jason.Y
 * @since 2016-01-22
 */
@Service("cpcService")
public class CpcServiceImpl extends GenericServiceImpl<Cpc> implements CpcService {

	public static String GetCodeRequest = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
	
	public static String GetAccessTokenRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

	public static boolean flag = false;
	
	public static String codeOverall = null;
	
	public int maxAge;
	
    @Autowired
    private GenericJdbcSupport genericJdbcSupport;

	@Override
	public Map<String,Object> getOpenidFromWinxin(HttpServletRequest request, HttpServletResponse response) {
		
		Map<String,Object> map = new HashMap<String,Object>();
		// get property from resource
		ClassPathResource resource = new ClassPathResource("/config/application.properties");
		Properties props = null;
		try {
			props = PropertiesLoaderUtils.loadProperties(resource);
		} catch (IOException e) {
			e.printStackTrace();
		}
		maxAge = Integer.valueOf(props.getProperty("cpc.maxage"));

		// 1 code为空，从cookie获取
		Cookie cookie = CookieUtil.getCookieByName(request, "cpc_code");
		// System.out.println("NullPointerException cookie ==============>" +
		// cookie);

		if (cookie != null) {
			codeOverall = cookie.getValue();
			//System.out.println("doGet ''.equals(codeOverall)  ==============>" + "".equals(codeOverall));
		}

		// 第一次请求微信服务端获取code
		if (codeOverall == null || "".equals(codeOverall)) {
			requestRemoteLocation(request, response);
			codeOverall = request.getParameter("code");
			CookieUtil.addCookie(response, "cpc_code", codeOverall, maxAge);

		} else {
			flag = true;
		}

		String source = request.getParameter("source");
		String cpcid = request.getParameter("cpcid");
		
		map.put("source", source);
		map.put("cpcid", cpcid);
		
		String openId = null;

		if (flag && codeOverall != null && !"".equals(codeOverall)) {
			// System.out.println("3 codeOverall ==============>" +codeOverall);
			try {
				
				 if (!"authdeny".equals(codeOverall)) {
					// 获取网页授权access_token
					WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken("wxcb9206a029e6edba","680b3ef0ad0838528d7c2fe082b40065", codeOverall);
					// 用户标识
					openId = weixinOauth2Token.getOpenid();
				 }
				

				// 第一次从微信服务端拿到 openId后 添加至 cookie，默认生命周期设置
				// 5分钟(code只允许用一次，5分钟内有效)
				if (openId != null && !"".equals(openId)) {
					CookieUtil.addCookie(response, "cpc_openid", openId, maxAge);
					// System.out.println("addCookie openId ==============>" +
					// openId);
				}

			} catch (Exception e) {
				// 1 code为空，从cookie获取
				cookie = CookieUtil.getCookieByName(request, "cpc_openid");
				// System.out.println("NullPointerException cookie
				// ==============>" + cookie);

				if (cookie != null) {
					openId = cookie.getValue();
				} else {
					e.printStackTrace();
				}
			}

			System.out.println("final --> openId ==============>" + openId);
		}

		if(openId!=null && !"".equals(openId)){
			map.put("openid", openId);
		}
		
		
		return map;

	}

	public static String getCodeRequest(HttpServletRequest request) {

		String requestUrl = "http://" + request.getServerName() // 服务器地址
				//+ ":" + request.getServerPort() // 端口号
				+ request.getContextPath() // 项目名称
				+ request.getServletPath() // 请求页面或其他地址
				+ "?source=" + request.getParameter("source")
				+ "&cpcid=" + request.getParameter("cpcid");

		System.out.println("requestUrl ==============>" + requestUrl);
		
		GetCodeRequest = GetCodeRequest.replace("APPID", urlEnodeUTF8("wxcb9206a029e6edba"));
		GetCodeRequest = GetCodeRequest.replace("REDIRECT_URI", urlEnodeUTF8(requestUrl));
		GetCodeRequest = GetCodeRequest.replace("SCOPE", "snsapi_base");

		return GetCodeRequest;
	}

	private void requestRemoteLocation(HttpServletRequest request, HttpServletResponse response) {
		// 要重定向的新位置
		String site = new String(getCodeRequest(request));
		response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
		response.setHeader("Location", site);
	}
	
	public static String urlEnodeUTF8(String str) {
		String result = str;
		try {
			result = URLEncoder.encode(str, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public void insertPv(String openid) {
		
		String insertSql = "insert into boyle.cpc_pv(cpcid,openid,source,useragent,create_time,ip,cpc_consume_id) values(1,1,1,1,1,1,1) ";
		
		Map<String, Object> map = new HashMap<String, Object>(7);
		map.put("cpcid", 1);
		map.put("openid", openid);
		map.put("source", 1);
		map.put("useragent", 1);
		map.put("createTime", 1);
		map.put("ip", 1);
		map.put("cpcConsumeId", 1);
		
		genericJdbcSupport.executeSQL(insertSql, map);
		
		System.out.println(map);
		
	}
	

}
